package com.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * Author Name: Justice
 * Project Name: zookeepercurator
 * File Name: Lock1
 * Package Name: com.curator
 * Date: 2020-02-22 22:08
 * Copyright (c) 2020,All Rights Reserved.
 */


public class Lock1 {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static int i = 10;

    private static void deNum() {
        i--;
        System.err.println(i);
    }

    public static void main(String[] args) throws IOException {
        // 超时后等1秒再重试,最多重试5次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
        final CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(AddressUtil.ADDRESS)
                .connectionTimeoutMs(10000).sessionTimeoutMs(10000)
                .retryPolicy(retryPolicy)
                .build();
        curatorFramework.start();
        for (int j = 0; j < 10; j++) {
            new Thread() {
                @Override
                public void run() {
                    // 通过zookeeper来获取锁
                    // 创建锁
                    InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/testlock03");
                    try {
                        // 此处等待, 目的是等所有的线程都创建完成了再执行
                        countDownLatch.await();
                        // 抢锁, 抢到的就会执行, 抢不到等待
                        lock.acquire();
                        deNum();
                        System.err.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss|SSS").format(new Date()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
        // 放行
        countDownLatch.countDown();
        System.in.read();
    }
}
